import React, { Component, Fragment } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import AddProducts from './addProducts'
import { uploadUrl } from '@/config/index'
import {
  Card,
  Tabs,
  message,
  Button,
  Table,
  Select,
  Modal,
  Form,
  Input,
  Icon,
  Upload,
  Popconfirm
} from 'antd'
import { connect } from 'dva'
import { LZFormItem } from '@/components/LZForm'
import SpikeService from './services'
import { getToken } from '@/utils/localStorage'
import { router } from 'umi'
import { isEqual } from 'lodash'
import RouterWillLeave from '@/components/RouterWillLeave'

const { TabPane } = Tabs
const formItemLayout = {
  labelCol: {
    xs: { span: 12 },
    sm: { span: 3 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
}
const formItemLayoutModal = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
}

const defaultDetail = {
  bottom: [],
  labelProducts: {},
  products: [],
  adPic: '',
  subtitle: ''
}

@connect()
@Form.create()
class TopicDetail extends Component {
  state = {
    id: '',
    tabVisible: false,
    bottomVisible: false,
    title: '', //modal的标题
    imgSrc: '',
    fileList: [],
    tabActiveKey: '',
    pageNumber: 1,
    pageSize: 10,
    tabInfo: [], //当前tab的信息
    addProductVisible: false,
    detail: {},
    loading: true,
    addTabConfirmLoading: false,
    channelData: [],
    addProductType: '',
    bottomFileList: [],
    isSubmit: false,
    originData: {}
  }

  footerLinkColumns = [
    {
      title: '底部宣传图片',
      dataIndex: 'pic',
      align: 'center',
      render: text => <img src={text} className="table-cell-img" alt="" />
    },
    {
      title: '跳转链接',
      dataIndex: 'url',
      align: 'center'
    },
    {
      title: '排序',
      dataIndex: 'sort',
      align: 'center'
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      render: (text, record) => (
        <div className="table-action">
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => this.deleteBottomProduct(record)}
          >
            <a>删除</a>
          </Popconfirm>
        </div>
      )
    }
  ]

  componentDidMount() {
    const {
      match: {
        params: { id }
      }
    } = this.props
    this.getDetail(id)
  }

  getGoodsColumn = isScroll => {
    return [
      {
        title: '商品ID',
        dataIndex: 'productId',
        align: 'center'
      },
      {
        title: '商品名称',
        dataIndex: 'productName',
        align: 'center',
        render: (text, record) => {
          return record.productName || record.name
        }
      },
      {
        title: '商品价格',
        dataIndex: 'price',
        align: 'center',
        render: (text, record) => {
          const cyclePrice =
            record.cyclePrices &&
            record.cyclePrices[0] &&
            record.cyclePrices[0].price
          return text || cyclePrice || ''
        }
      },
      {
        title: '操作',
        align: 'center',
        key: 'action',
        render: (text, record) => {
          const fn = isScroll
            ? this.deleteScrollProduct
            : this.deleteLabelProduct
          return (
            <div className="table-action">
              <Popconfirm title="确定要删除吗？" onConfirm={() => fn(record)}>
                <a>删除</a>
              </Popconfirm>
            </div>
          )
        }
      }
    ]
  }

  getDetail = id => {
    this.setState({
      loading: true
    })
    SpikeService.getTopicSpecialPageDetail({
      indexId: id,
      type: 'TOPIC'
    })
      .then(res => {
        let fileList = []
        let detail = defaultDetail
        if (res.responseType === 'SUCCESS' && !res.data) {
          fileList = []
        } else {
          fileList = [{ uid: res.id, url: res.adPic }]
          detail = res
        }
        this.setState({
          id,
          detail,
          fileList,
          originData: detail
        })
      })
      .finally(() => {
        this.setState({
          loading: false
        })
      })
  }

  deleteScrollProduct = record => {
    const { detail } = this.state
    const { products } = detail
    const index = products.findIndex(f => f.productId === record.productId)
    products.splice(index, 1)
    this.setState({
      detail: {
        ...detail,
        products
      }
    })
  }

  deleteLabelProduct = record => {
    const { detail } = this.state
    const { labelProducts } = detail
    const { label } = record
    const index = labelProducts[label].findIndex(
      f => f.productId === record.productId
    )
    labelProducts[label].splice(index, 1)
    this.setState({
      detail: {
        ...detail,
        labelProducts
      }
    })
  }

  deleteBottomProduct = record => {
    const { detail } = this.state
    const { bottom } = detail
    const index = bottom.findIndex(f => f.id === record.id)
    bottom.splice(index, 1)
    this.setState({
      detail: {
        ...detail,
        bottom
      }
    })
  }

  //获取上架渠道
  getChannel = () => {
    const { dispatch } = this.props
    dispatch({
      type: 'tab/getChannel',
      payload: {},
      callback: res => {
        this.setState({
          channelData: res
        })
      }
    })
  }

  onTabChange = key => {
    this.setState({
      tabActiveKey: key
    })
  }

  addTag = () => {
    this.setState({
      tagVisible: true,
      title: '添加标签'
    })
  }

  addBottom = () => {
    this.setState({
      bottomVisible: true,
      title: '添加跳转链接'
    })
  }

  //modal的确认
  handleOk = () => {
    this.props.form.validateFields(['aa'], (err, value) => {
      if (!err) {
        this.setState({
          tabInfo: [],
          addTabConfirmLoading: true
        })
        if (this.state.title === '新增') {
          //增加
          this.props.dispatch({
            type: 'tab/addTab',
            payload: {
              name: value.aa.name,
              indexSort: value.aa.sort,
              tabImgUrl: value.aa.url,
              channerIds: value.aa.channel
            },
            callback: res => {
              if (res.msg === '操作成功') {
                this.setState(
                  {
                    tabVisible: false,
                    addTabConfirmLoading: false
                  },
                  () => {
                    this.props.form.resetFields()
                    this.getTab()
                  }
                )
              } else {
                this.setState({
                  addTabConfirmLoading: false
                })
                message.error(res.msg)
              }
            }
          })
        } else {
          //修改
          this.props.dispatch({
            type: 'tab/updateTab',
            payload: {
              id: this.state.tabInfo[0].id,
              name: value.aa.name,
              indexSort: value.aa.sort,
              tabImgUrl: value.aa.url,
              channerIds: value.aa.channel
            },
            callback: res => {
              if (res.msg === '操作成功') {
                this.setState(
                  {
                    tabVisible: false,
                    addTabConfirmLoading: false
                  },
                  () => {
                    this.props.form.resetFields()
                    this.getTab()
                  }
                )
              } else {
                message.error(res.msg)
              }
            }
          })
        }
      }
    })
  }

  // 上传的回调
  handleUploadChange = ({ file, fileList, event }, type) => {
    if (file.status === 'done') {
      this.setState({
        imgSrc: file.response.data
      })
    }
    let payload
    if (type === 'bottom') {
      payload = {
        bottomFileList: fileList
      }
    } else {
      payload = {
        fileList
      }
    }
    this.setState(payload)
  }
  // 上传后预览的回调
  handlePreview = () => {
    this.setState({
      imgVisible: true
    })
  }
  //上传后下载的回调
  onDownload = file => {
    return window.open(this.state.imgSrc)
  }
  // 上传后删除的回调
  onRemove = () => {
    this.setState({
      fileList: [],
      imgSrc: ''
    })
  }

  //分页，下一页
  onChange = pageNumber => {
    // alert(pageNumber)
    this.setState(
      {
        pageNumber: pageNumber
      },
      () => {
        this.getProduct()
      }
    )
  }
  showTotal = () => {
    return `共有${this.state.total}条`
  }
  //切换每页数量
  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize: pageSize,
        pageNumber: 1
      },
      () => {
        this.getProduct()
      }
    )
  }
  //选择商品
  addProduct = type => {
    this.setState({
      addProductVisible: true,
      addProductType: type
    })
  }
  handleProductCancel = () => {
    this.setState({
      addProductVisible: false
    })
  }

  // 选择商品时，会把选择的商品数据传过来，然后处理之后置入相应的数据中
  selectProducts = rows => {
    const { addProductType: key, detail, tabActiveKey } = this.state
    let _rows = [...rows]
    if (key === 'products') {
      let _list = detail[key] ? detail[key] : []
      _rows = _list.concat(_rows)
    } else if (key === 'labelProducts') {
      const { labelProducts = {} } = detail
      const tabs = Object.keys(labelProducts || [])
      console.log(tabs, 'eaeaea')
      console.log(rows, 'rowsrows')
      rows.map(row => {
        if (tabs.includes(row.label)) {
          labelProducts[row.label].push(row)
        }
      })
      this.setState({
        addProductVisible: false,
        detail: {
          ...this.state.detail,
          labelProducts
        }
      })
      return
    } else {
      let _list = detail[key][tabActiveKey] ? detail[key][tabActiveKey] : []
      _list = _list.concat(_rows)
      _rows = {
        ...detail[key],
        [tabActiveKey]: _list
      }
    }
    this.setState({
      addProductVisible: false,
      detail: {
        ...this.state.detail,
        [key]: _rows
      }
    })
  }

  cancel = () => {
    router.push('/configure/spike')
  }

  submit = () => {
    const { detail, id } = this.state
    const { form } = this.props
    form.validateFields((err, values) => {
      if (!err) {
        let _bottom = detail.bottom || []
        const bottom = _bottom.map(value => {
          return {
            ...value,
            indexId: detail.indexId
          }
        })
        console.log(bottom)
        SpikeService.saveTopicSpecialPage({
          ...detail,
          bottom,
          indexId: id,
          subtitle: values.subtitle,
          adPic: values.adPic.file
            ? values.adPic.file.response.data
            : values.adPic
        }).then(res => {
          message.success('保存成功')
          this.cancel()
        })
      }
    })
  }

  deleteTag = tabActiveKey => {
    const { detail } = this.state
    if (detail.labelProducts) {
      delete detail.labelProducts[tabActiveKey]
      this.setState({
        detail
      })
    }
  }

  uploadButton = () => {
    return (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传图片</div>
      </div>
    )
  }

  renderAddBottom = () => {
    const {
      title,
      bottomVisible,
      confirmLoading,
      detail,
      imgSrc,
      bottomFileList
    } = this.state
    const { form } = this.props
    let { bottom = [] } = detail
    const { getFieldDecorator } = form
    const imgUploadValidate = {
      validator: (rule, value, callback) => {
        if (!value && imgSrc) {
          callback('图片不能为空')
        }
        callback()
      }
    }
    const handleOk = () => {
      form.validateFields(['pic', 'url', 'sort'], (err, values) => {
        if (!err) {
          if (!bottom) {
            bottom = []
          }
          bottom.push({
            ...values,
            pic: imgSrc
          })
          this.setState({
            bottomVisible: false,
            detail: {
              ...detail,
              bottom
            }
          })
        }
      })
    }

    return (
      <Modal
        title={title}
        visible={bottomVisible}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        destroyOnClose={true}
        onCancel={() => {
          this.setState({
            bottomVisible: false
          })
        }}
      >
        <Form {...formItemLayoutModal}>
          <LZFormItem
            field="pic"
            label="底部宣传图片"
            getFieldDecorator={getFieldDecorator}
            required
            rules={[imgUploadValidate]}
          >
            <Upload
              accept="image/*"
              action={uploadUrl}
              headers={{
                token: getToken()
              }}
              fileList={bottomFileList}
              listType="picture-card"
              onPreview={this.handlePreview} //预览
              onRemove={this.onRemove} //删除
              onChange={evt => this.handleUploadChange(evt, 'bottom')}
            >
              {bottomFileList.length >= 1 ? null : this.uploadButton()}
            </Upload>
          </LZFormItem>
          <LZFormItem
            field="url"
            label="跳转链接"
            getFieldDecorator={getFieldDecorator}
            requiredMessage="跳转链接不能为空"
          >
            <Input placeholder="请输入" />
          </LZFormItem>
          <LZFormItem
            field="sort"
            label="排序"
            getFieldDecorator={getFieldDecorator}
            requiredMessage="排序不能为空"
          >
            <Input placeholder="请输入" />
          </LZFormItem>
        </Form>
      </Modal>
    )
  }

  renderAddTag = () => {
    const {
      title,
      tagVisible,
      confirmLoading,
      detail,
      tabActiveKey
    } = this.state
    const { form } = this.props
    let { labelProducts = {}, name } = detail
    const { getFieldDecorator } = form
    const handleOk = () => {
      form.validateFields(['label'], (err, values) => {
        if (!err) {
          if (!labelProducts) {
            labelProducts = {}
          }
          labelProducts[values.label] = []
          this.setState({
            tagVisible: false,
            tabActiveKey: values.label,
            detail: {
              ...detail,
              labelProducts
            }
          })
        }
      })
    }
    return (
      <Modal
        title={title}
        visible={tagVisible}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        destroyOnClose={true}
        onCancel={() => {
          this.setState({
            tagVisible: false
          })
        }}
      >
        <Form {...formItemLayoutModal}>
          <LZFormItem
            field="label"
            label="标签名称"
            getFieldDecorator={getFieldDecorator}
            requiredMessage="标签名称不能为空"
            initialValue={name}
          >
            <Input placeholder="请输入" />
          </LZFormItem>
        </Form>
      </Modal>
    )
  }

  renderRouterWillLeave = () => {
    const { originData, isSubmit, detail } = this.state
    const values = this.props.form.getFieldsValue()

    const payload = {
      ...detail,
      subtitle: values.subtitle
    }
    const isPrompt = !isEqual(payload, originData)
    console.log(isPrompt, payload, originData)
    return <RouterWillLeave isPrompt={isPrompt} isSubmit={isSubmit} />
  }

  render() {
    let {
      loading,
      imgSrc,
      fileList,
      tabActiveKey,
      detail,
      addProductVisible,
      addProductType
    } = this.state
    const {
      title: topicTitle,
      subtitle,
      products,
      labelProducts = {},
      bottom = []
    } = detail
    const tabs = Object.keys(labelProducts || [])
    tabActiveKey = tabs.includes(tabActiveKey) ? tabActiveKey : tabs[0]
    const { getFieldDecorator } = this.props.form

    return (
      <PageHeaderWrapper className="topic">
        {this.renderRouterWillLeave()}
        <Card bordered={false} className="mt-20">
          <Form {...formItemLayout}>
            <Form.Item label="专场类型">主题专场</Form.Item>
            <Form.Item label="专场标题">{topicTitle}</Form.Item>
            <Form.Item label="宣传图片">
              {getFieldDecorator('adPic', {
                rules: [
                  {
                    validator: (rule, value, callback) => {
                      if (!value && imgSrc) {
                        callback('图片不能为空')
                      }
                      callback()
                    }
                  }
                ],
                initialValue: imgSrc ? imgSrc : detail.adPic
              })(
                <Upload
                  accept="image/*"
                  action={uploadUrl}
                  listType="picture-card"
                  headers={{
                    token: getToken()
                  }}
                  fileList={fileList}
                  onPreview={this.handlePreview} //预览
                  onRemove={this.onRemove} //删除
                  onDownload={this.onDownload}
                  onChange={this.handleUploadChange}
                >
                  {fileList.length >= 1 ? null : this.uploadButton()}
                </Upload>
              )}
            </Form.Item>
            <LZFormItem
              label="页面子标题"
              field="subtitle"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="页面子标题不能为空"
              initialValue={subtitle}
            >
              <Input className="w-240" placeholder="请输入" />
            </LZFormItem>
          </Form>
        </Card>

        <Card bordered={false} className="mt-20">
          <Form.Item label="添加滑动商品" required>
            <div>
              <Button
                type="primary"
                ghost
                className="w-80 mb-18"
                onClick={() => this.addProduct('products')}
              >
                新增
              </Button>
              <Table
                columns={this.getGoodsColumn(true)}
                dataSource={products}
                rowKey={record => record.productId}
                pagination={false}
              />
            </div>
          </Form.Item>
        </Card>

        <Card bordered={false} className="mt-20">
          <Form.Item label="添加标签和商品" required>
            <Tabs
              size="small"
              activeKey={tabActiveKey}
              onChange={this.onTabChange}
              tabBarExtraContent={
                <div>
                  <Button type="primary" ghost onClick={this.addTag}>
                    添加标签
                  </Button>
                  <Popconfirm
                    title="确定要删除吗？"
                    onConfirm={() => this.deleteTag(tabActiveKey)}
                  >
                    <Button>删除标签</Button>
                  </Popconfirm>
                </div>
              }
            >
              {tabs &&
                tabs.map(item => (
                  <TabPane tab={item} key={item}>
                    <Button
                      type="primary"
                      ghost
                      onClick={() => this.addProduct('labelProducts')}
                      style={{ margin: '10px 10px' }}
                    >
                      添加商品
                    </Button>
                    <Table
                      loading={loading}
                      columns={this.getGoodsColumn()}
                      dataSource={labelProducts[tabActiveKey]}
                      rowKey={record => record.id}
                      pagination={false}
                    ></Table>
                  </TabPane>
                ))}
            </Tabs>
          </Form.Item>
        </Card>

        <Card bordered={false} className="mt-20">
          <Form.Item label="底部跳转链接" required>
            <div>
              <Button
                type="primary"
                style={{ margin: '10px' }}
                ghost
                onClick={this.addBottom}
              >
                新增
              </Button>
              <Table
                columns={this.footerLinkColumns}
                dataSource={bottom}
                rowKey={record => record.id}
                pagination={false}
              ></Table>
            </div>
          </Form.Item>
        </Card>

        <Card bordered={false} style={{ margin: '20px 0' }}>
          <div>
            <Button onClick={this.cancel}>取消</Button>

            <Button type="primary" onClick={this.submit}>
              确定
            </Button>
          </div>
        </Card>

        <AddProducts
          visible={addProductVisible}
          selectProducts={this.selectProducts}
          type={addProductType}
          labels={tabs}
          scrollProductCancel={this.handleProductCancel}
        />

        {this.renderAddTag()}
        {this.renderAddBottom()}
      </PageHeaderWrapper>
    )
  }
}

export default TopicDetail
